package net.xdclass.xdclassmq.jms;

import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Service;

@Service
public class TransactionListenerImpl implements TransactionListener {
    @Override
    public LocalTransactionState executeLocalTransaction(Message message, Object o) {

        System.out.println("======executeLocalTransaction======");
        String body = new String(message.getBody());
        String key = message.getKeys();
        String transactionId = message.getTransactionId();
        System.out.println("transactionId="+transactionId+",key="+key+",body"+body);

        //TODO 执行本地事务begin

        //TODO 执行本地事务end

        //以下代码为模拟使用
        int status = Integer.parseInt(o.toString());
        //二次确认消息，事务执行成功，消费者可以消费
        if(status == 1){
            return LocalTransactionState.COMMIT_MESSAGE;
        }
        //二次确认消息，事务执行失败，回滚消息，broker端会删除半消息
        if(status == 2){
            return LocalTransactionState.ROLLBACK_MESSAGE;
        }
        //二次确认消息，事务执行结果未知，或什么都不响应，需要broker回查消息
        if(status == 3){
            return LocalTransactionState.UNKNOW;
        }
        return null;
    }

    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {

        System.out.println("======checkLocalTransaction======");
        String body = new String(messageExt.getBody());
        String key = messageExt.getKeys();
        String transactionId = messageExt.getTransactionId();
        System.out.println("transactionId="+transactionId+",key="+key+",body"+body);

        //要么commit，要么rollback
        //可以根据key去检查本地事务消息是否完成

        return LocalTransactionState.COMMIT_MESSAGE;
    }
}
